package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.enums.account.InvitaionCodeStatus;
import com.ndp.fb.rdb.api.InvitationCodeRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.PstAssign;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.InvitationCode;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by elvisxiong on 7/8/15.
 */
@Service
public class InvitationCodeRdbServiceImpl extends DaoTemplate implements InvitationCodeRdbService {

    @Override
    public Long insertInvitationCode(final InvitationCode invitationCode) {
        String sql = "INSERT INTO invitation_code(org_id,role_id,code,status,expire_date) values (?,?,?,?,?)";
        PstAssign psta = new PstAssign() {
            @Override
            public void setParam(PreparedStatement ps) throws SQLException {
                ps.setLong(1, invitationCode.getOrgId());
                ps.setLong(2, invitationCode.getRoleId());
                ps.setString(3, invitationCode.getCode());
                ps.setInt(4, invitationCode.getStatus());
                ps.setDate(5,new Date(invitationCode.getExprieDate()));
            }
        };
        return saveResultId(sql,psta);
    }

    @Override
    public Long updateInvitaionCodeStatus(Long id, InvitaionCodeStatus status) {
        String sql = "UPDATE invitation_code SET status = ? where id = ?";
        int resultId = getJdbcTemplate().update(sql, new Object[]{status.ordinal(), id});
        return new Long(resultId);
    }


    @Override
    public InvitationCode getInvitationCodeByCode(String code, Boolean expireSwitch) {
        StringBuffer sql = new StringBuffer("SELECT * FROM invitation_code WHERE code =? AND status = 1 ");
        if (expireSwitch.booleanValue()) {
            sql.append("AND expire_date >= NOW()");
        }
        return findOne(sql.toString(), new Object[]{code}, DefaultRowMapper.autoRowMapper(InvitationCode.class));
    }

    @Override
    public Integer getCountByOrgId(Long orgId,String roles) {
        //注意此处将外部美宣排除了
        String sql = "SELECT COUNT(*) FROM `user` t  WHERE t.`status` = 0 AND t.`org_id` = " +
                orgId +" AND t.id IN (SELECT DISTINCT user_role.`user_id` FROM `user_role` WHERE role_id IN ("+ roles +"))";
        return getJdbcTemplate().queryForObject(sql, Integer.class);
    }
}
